package com.ssy.lingxi.contract.handler.notify;

import cn.hutool.json.JSONUtil;
import com.rabbitmq.client.Channel;
import com.ssy.lingxi.contract.api.model.constant.ContractConstants;
import com.ssy.lingxi.contract.api.model.vo.request.ContractOrderAmountLogRequest;
import com.ssy.lingxi.contract.service.IContractManageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 *  采购订单-新增/修改/取消订单
 * @author ds
 * @version 2.0.0
 * @date 2021/4/14 18:24
 */
@Component
public class OrderMessageHandler {

    @Resource
    private IContractManageService contractManageService;

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @RabbitListener(queues = ContractConstants.CONTRACT_ORDER_CHANGE_QUEUE,ackMode ="MANUAL")
    public void handler(Message message, Channel channel) throws IOException {
        String bodyStr = new String(message.getBody());
        try {
            log.info("处理合同订单队列通知,body:{}",bodyStr);
            ContractOrderAmountLogRequest request=JSONUtil.toBean(bodyStr, ContractOrderAmountLogRequest.class);
            contractManageService.updateContractFreeAmount(request);
            //确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch(DataIntegrityViolationException e){//唯一约束冲突异常
            log.info("重复消费通知,body:{}",bodyStr);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e){
            log.error("处理合同订单变更通知异常,body:{},异常消息：",bodyStr,e);
            log.info("处理合同订单变更通知异常,message:{}",message);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
